import { Controller,Post, Body, Inject, Query, Get, UnauthorizedException } from '@nestjs/common';
import { UserService } from './user.service';
import { LoginUserDto } from './dto/login-user.dto';
import { JwtService } from '@nestjs/jwt';
import { ApiBearerAuth,ApiTags } from "@nestjs/swagger"

@Controller('user')
@ApiBearerAuth()
@ApiTags('User')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Inject(JwtService)
  private jwtService : JwtService;
    
  @Post('login')
  async login(@Body() loginUser: LoginUserDto) {
      const user = await this.userService.login(loginUser);
    
      const access_token = this.jwtService.sign(
        { userId: user.id, username: user.username },
        { expiresIn: '30s' },
      )

      const refresh_token = this.jwtService.sign(
        { userId: user.id },
        { expiresIn: '1h' }
      )

      return {
        access_token,
        refresh_token
      }

  }

  //利用refresh_token 重新获取 access_token
  @Get('refresh')
  async refresh(@Query('refresh_token') refreshToken: string) {
    try{
      const payload = this.jwtService.verify(refreshToken);
      const user = await this.userService.findId(payload.userId);

      const access_token = this.jwtService.sign(
        { userId: user.id, username: user.username },
        { expiresIn: '30s' },
      )

      //如果7天内重新登录,每次都会重新刷新refresh_token的过期时间
      const refresh_token = this.jwtService.sign({
        userId: user.id
      }, {
        expiresIn: '1h'
      });

      return {
        access_token,
        refresh_token
      } 
    
        
    }catch(e){
      throw new UnauthorizedException('token 已失效，请重新登录');
    }
  }
  
}
